package com.github.lh.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author <a href="mailto: 393803588@qq.com">刘涵(Hanl)</a>
 * By 2017/12/1
 */
@Configuration
@ConditionalOnClass(name = {"com.alibaba.druid.pool.DruidDataSource"})
@EnableConfigurationProperties(DruidAutoConfiguration.DruidAdminProperties.class)
public class DruidAutoConfiguration {


    @Bean
    public ServletRegistrationBean statViewServlet(DruidAdminProperties props) {
        ServletRegistrationBean srb = new ServletRegistrationBean(new StatViewServlet(), props.getUrlMapping());
        srb.addInitParameter("loginUsername", props.getUser());
        srb.addInitParameter("loginPassword", props.getPass());
        return srb;
    }

    @Bean
    public FilterRegistrationBean statFilter(DruidAdminProperties props) {
        FilterRegistrationBean frb = new FilterRegistrationBean(new WebStatFilter());
        frb.addUrlPatterns("/*");
        frb.addInitParameter("exclusions", "*.js,*.css,*.jpg,*.png,*.gif, " + props.urlMapping);
        return frb;
    }

    @ConfigurationProperties(prefix = "druid.admin")
    public static class DruidAdminProperties {

        private String urlMapping = "/druid/*";
        private String user = "admin";
        private String pass = "admin";

        public String getUrlMapping() {
            return urlMapping;
        }

        public void setUrlMapping(String urlMapping) {
            this.urlMapping = urlMapping;
        }

        public String getUser() {
            return user;
        }

        public void setUser(String user) {
            this.user = user;
        }

        public String getPass() {
            return pass;
        }

        public void setPass(String pass) {
            this.pass = pass;
        }
    }
}
